import json

from django.db.models import Q
from django.http import JsonResponse
from django.shortcuts import HttpResponse, render
from rest_framework import generics, status
from rest_framework.decorators import api_view
from rest_framework.response import Response

from .models import SonarProfile
from .serializers import *


class SonarList(generics.ListAPIView):
    queryset = SonarProfile.objects.all()
    serializer_class = SonarProfileSerializers


class SonarDetail(generics.RetrieveAPIView):
    queryset = SonarProfile.objects.all()
    serializer_class = SonarProfileSerializers


class SonarDetail(generics.RetrieveUpdateDestroyAPIView):
    queryset = SonarProfile.objects.all()
    serializer_class = SonarProfileSerializers


@api_view(["GET"])
def SonarListView(request):
    qs_all = SonarProfile.objects.all()
    qs = qs_all
    if request.method == "GET":
        print("1" * 111)
        print(request.GET)
        try:
            f5 = int(request.GET["Freq_5"])
            qs = qs.filter(**{
                "Freq_5__gte": f5 - 4
            }).filter(**{"Freq_5__lte": f5 + 4})
        except:
            pass
        try:
            f4 = int(request.GET["Freq_4"])
            qs = qs.filter(**{
                "Freq_4__gte": f4 - 4
            }).filter(**{"Freq_4__lte": f4 + 4})
        except:
            pass
        try:
            f3 = int(request.GET["Freq_3"])
            qs = qs.filter(**{
                "Freq_3__gte": f3 - 4
            }).filter(**{"Freq_3__lte": f3 + 4})
        except:
            pass
        try:
            f2 = int(request.GET["Freq_2"])
            qs = qs.filter(**{
                "Freq_2__gte": f2 - 4
            }).filter(**{"Freq_2__lte": f2 + 4})
        except:
            pass
        try:
            f1 = int(request.GET["Freq_1"])
            qs = qs.filter(**{
                "Freq_1__gte": f1 - 4
            }).filter(**{"Freq_1__lte": f1 + 4})
        except:
            pass
        try:
            Blades = int(request.GET["Blades"])
            qs = qs.filter(**{"Blades__exact": Blades})
        except:
            pass
        try:
            TPK = int(request.GET["TPK"])
            qs = qs.filter(**{"TPK__exact": TPK})
        except:
            pass
        try:
            active_f = int(request.GET["Active_freq"])
            qs = qs.filter(**{
                "Active_freq__gte": active_f - 3
            }).filter(**{"Active_freq__lte": active_f + 3})
        except:
            pass

        pd = SonarProfileSerializers(qs, many=True)
        data = json.dumps({
            "code": 0,
            "msg": "",
            "count": len(pd.data),
            "data": pd.data,
        })
        return HttpResponse(data, content_type="application/json")
